﻿using AppWebApi.Model;
using AppWebApi.Model.Dto;
using Microsoft.AspNetCore.Mvc;
using SqlSugar;

namespace AppWebApi.Controllers
{
    [Route("api/[controller]/[action]")]
    [ApiController]
    public class RecordController : BaseApiController
    {
        private readonly ISqlSugarClient _db;
        public RecordController(ISqlSugarClient db)
        {
            this._db = db;
        }

        /// <summary>
        /// 分页获取记录
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        [HttpGet]
        public async Task<MessageModel<PageModel<Record>>> GetListByPage([FromQuery] FilterDto dto)
        {
            int pageIndex = dto.pageIndex;
            int pageSize = dto.pageSize;
            var exp = Expressionable.Create<Record>()
                           .And((p) => p.Name.Contains(dto.keyword))
                           .ToExpression();
            RefAsync<int> totalCount = 0;
            var list = await _db.Queryable<Record>()
                .WhereIF(exp != null, exp)
                .ToPageListAsync(dto.pageIndex, dto.pageSize, totalCount);

            var data = new PageModel<Record>(pageIndex, totalCount, pageSize, list);
            return SuccessPage(data);
        }

        /// <summary>
        /// 添加
        /// </summary>
        /// <param name="CardInfo"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<MessageModel<string>> Post([FromBody] Record record)
        {
            record.Id = SnowflakeHelper.Instance().GetId();
            var insert = await _db.Insertable(record).ExecuteReturnEntityAsync();
            var list = await _db.Queryable<Config>().Where(a => a.Name == record.Name).ToListAsync();
            if (insert != null && list.Count > 0)
            {
                var config = list[0];
                if (record.Flag == 1) //1是启动时间  0是关闭时间
                {
                    config.LastStartTime = record.RecordTime;
                }
                else
                {
                    config.LastCloseTime = record.RecordTime;
                }
                await _db.Updateable(config).WhereColumns(it => new { it.Id }).ExecuteCommandAsync();
            }
            return insert.Id > 0 ? Success(insert.Id.ToString(), "添加成功") : Failed("添加失败");
        }

        ///// <summary>
        ///// 更新
        ///// </summary>
        ///// <param name="CardInfo"></param>
        ///// <returns></returns>
        //[HttpPut]
        //public async Task<MessageModel<string>> Put([FromBody] Record record)
        //{
        //    if (record == null || record.Id <= 0) return Failed("缺少参数");
        //    bool isRet = await _db.Updateable(record).ExecuteCommandHasChangeAsync();
        //    return isRet ? Success(record.Id.ToString(), "更新成功") : Failed("更新失败");
        //}
    }
}
